package com.zuilapsa.jmc.userInterfaces;

import java.net.*;
import java.io.*;

import com.zuilapsa.jmc.*;
import com.zuilapsa.jmc.userInterfaces.telnet.TelnetInterfaceSession;

public class TelnetInterface extends Thread implements UserInterface {
	public static final int BIND_DELAY = 5000;

	ServerSocket serverSocket = null;

	TelnetInterface deamon;

	public TelnetInterface() {
		super("TelnetInterfaceSession");
		deamon = this;
	}

	public void run() {
		// start listening
		while (true) {
			try {
				serverSocket = new ServerSocket(Configuration.getTelnetPort(),
						3);
				System.out.println(getName() + ": listening on port: "
						+ Configuration.getTelnetPort());
				break;
			} catch (IOException e) {
				System.out.println(getName() + ": Could not listen on port: "
						+ Configuration.getTelnetPort());
			}
			try {
				System.out.println(getName() + ": Will retry in " + BIND_DELAY
						+ "ms");
				Thread.sleep(BIND_DELAY);
			} catch (InterruptedException e) {
				System.err.println(e);
			}
		}

		// main loop
		Thread thisThread = Thread.currentThread();
		while (deamon == thisThread) {
			Socket clientSocket = null;
			try {
				clientSocket = serverSocket.accept();
				if (clientSocket.getInetAddress().isLoopbackAddress()) {
					new TelnetInterfaceSession(clientSocket).start();
					System.out.println(getName() + ": connection accepted");
				} else {
					System.err.println(getName() + ": unauthorized connection from "+clientSocket.getInetAddress().getHostAddress());
					clientSocket.close();
				}
			} catch (IOException e) {
				System.out.println(getName() + ": accept failed");
			}
		}

		// stop listening
		try {
			serverSocket.close();
		} catch (IOException e) {
			System.err.println(getName() + ": error closing listener");
		}
	}

	public void startStopping() {
		deamon = null;
	}

}
